package com.qust.endecryptionmanager.utils.loadBalance;


import com.alibaba.fastjson2.JSON;
import com.qust.endecryptionmanager.pojo.ZkNode;

import java.util.ArrayList;
import java.util.List;

public class WRR implements ILoadBalance<ZkNode> {
    //所有节点的列表
    List<ZkNode> list ;
    //总权重
    int total;

    //初始化节点列表
    public WRR(List<ZkNode> nodes){
        list = nodes;
        for (ZkNode node : nodes) {
            total += node.getWeight();
        }
    }

    //获取当前节点
    @Override
    public ZkNode select(){
        //执行前，current加权重
        for (ZkNode node : list) {
            node.setCurrentWeight(node.getCurrentWeight() + node.getWeight());
        }

        //遍历，取权重最高的返回
        ZkNode current = list.get(0);
        int i = 0;
        for (ZkNode node : list) {
            if (node.getCurrentWeight() > i){
                i = node.getCurrentWeight();
                current = node;
            }
        }
        current.setCurrentWeight(current.getWeight() - total);
        return current;
    }

//    public static void main(String[] args) {
//        ArrayList<ZkNode> nodes = new ArrayList<>();
//        nodes.add(new ZkNode("192.168.1.1",1));
//        nodes.add(new ZkNode("192.168.1.2",2));
//        nodes.add(new ZkNode("192.168.1.3",3));
//
//        WRR wrr = new WRR(nodes);
//        for (int i = 0; i < 15; i++) {
//            System.out.println(wrr.select());
//        }
//        System.out.println("---------------删除--------------");
//        nodes.remove(0);
//        for (int i = 0; i < 15; i++) {
//            System.out.println(wrr.select());
//        }
//
//    }
}

